<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"dttx123.gitee.io","root":"/blog/","scheme":"Gemini","version":"8.0.0-rc.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="模块化基本概念 在nodejs中，应用由模块组成，nodejs中采用commonJS模块规范。   一个js文件就是一个模块 每个模块都是一个独立的作用域，在这个而文件中定义的变量、函数、对象都是私有的，对其他文件不可见。   01-模块化的概念用于演示每一个模块都有自己单独的作用域  node中模块分类 1 核心模块 由 node 本身提供，不需要单独安装（npm），可直接引入使用   2 第三">
<meta property="og:type" content="article">
<meta property="og:title" content="模块化">
<meta property="og:url" content="http://dttx123.gitee.io/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/index.html">
<meta property="og:site_name" content="Starry Night">
<meta property="og:description" content="模块化基本概念 在nodejs中，应用由模块组成，nodejs中采用commonJS模块规范。   一个js文件就是一个模块 每个模块都是一个独立的作用域，在这个而文件中定义的变量、函数、对象都是私有的，对其他文件不可见。   01-模块化的概念用于演示每一个模块都有自己单独的作用域  node中模块分类 1 核心模块 由 node 本身提供，不需要单独安装（npm），可直接引入使用   2 第三">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2018-06-06T16:00:00.000Z">
<meta property="article:modified_time" content="2020-05-13T03:33:26.797Z">
<meta property="article:author" content="大春哥">
<meta property="article:tag" content="node 模块化">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://dttx123.gitee.io/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>模块化 | Starry Night</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line toggle-line-first"></span>
        <span class="toggle-line toggle-line-middle"></span>
        <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Starry Night</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">这就朕为你打下的江山</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          模块化
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-06-07 00:00:00" itemprop="dateCreated datePublished" datetime="2018-06-07T00:00:00+08:00">2018-06-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:33:26" itemprop="dateModified" datetime="2020-05-13T11:33:26+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="模块化"><a href="#模块化" class="headerlink" title="模块化"></a>模块化</h1><h2 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h2><blockquote>
<p>在nodejs中，应用由模块组成，nodejs中采用commonJS模块规范。</p>
</blockquote>
<ol>
<li>一个js文件就是一个模块</li>
<li>每个模块都是一个独立的作用域，在这个而文件中定义的变量、函数、对象都是私有的，对其他文件不可见。</li>
</ol>
<ul>
<li><code>01-模块化的概念</code>用于演示每一个模块都有自己单独的作用域</li>
</ul>
<h2 id="node中模块分类"><a href="#node中模块分类" class="headerlink" title="node中模块分类"></a>node中模块分类</h2><ul>
<li>1 核心模块<ul>
<li>由 node 本身提供，不需要单独安装（npm），可直接引入使用</li>
</ul>
</li>
<li>2 第三方模块<ul>
<li>由社区或个人提供，需要通过npm安装后使用</li>
</ul>
</li>
<li>3 自定义模块<ul>
<li>由我们自己创建，比如：tool.js 、 user.js</li>
</ul>
</li>
</ul>
<h3 id="核心模块"><a href="#核心模块" class="headerlink" title="核心模块"></a>核心模块</h3><ul>
<li>fs：文件操作模块</li>
<li>http：网络操作模块</li>
<li>path：路径操作模块</li>
<li>url: 解析地址的模块</li>
<li>querystring: 解析参数字符串的模块</li>
<li>基本使用：1 先引入  2 再使用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入模块</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br></pre></td></tr></table></figure>

<h3 id="第三方模块"><a href="#第三方模块" class="headerlink" title="第三方模块"></a>第三方模块</h3><ul>
<li>第三方模块是由 社区或个人 提供的</li>
<li>比如：mime模块/art-template/jquery…</li>
<li>基本使用：1 先通过npm下载 2 再引入 3 最后使用</li>
</ul>
<h3 id="用户自定义模块"><a href="#用户自定义模块" class="headerlink" title="用户自定义模块"></a>用户自定义模块</h3><ul>
<li>由开发人员创建的模块（JS文件）</li>
<li>基本使用：1 创建模块 2 引入模块</li>
<li>注意：自定义模块的路径必须以<code>./</code>获取<code>../</code>开头</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 加载模块</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'./a'</span>)     <span class="comment">// 推荐使用，省略.js后缀！</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'./a.js'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="模块的导入与导出"><a href="#模块的导入与导出" class="headerlink" title="模块的导入与导出"></a>模块的导入与导出</h2><h3 id="模块导入"><a href="#模块导入" class="headerlink" title="模块导入"></a>模块导入</h3><ul>
<li>通过<code>require(&quot;fs&quot;)</code>来加载模块</li>
<li>如果是第三方模块，需要先使用npm进行下载</li>
<li>如果是自定义模块，需要加上相对路径<code>./</code>或者<code>../</code>,可以省略<code>.js</code>后缀，如果文件名是<code>index.js</code>那么index.js也可以省略。</li>
<li>模块可以被多次引入，但是只会在第一次加载</li>
</ul>
<h3 id="模块导出"><a href="#模块导出" class="headerlink" title="模块导出"></a>模块导出</h3><ul>
<li>在模块的内部，<code>module</code>变量代表的就是当前模块，它的<code>exports</code>属性就是对外的接口，加载某个模块，加载的就是<code>module.exports</code>属性，这个属性指向一个空的对象。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//module.exports指向的是一个对象，我们给对象增加属性即可。</span></span><br><span class="line"><span class="comment">//module.exports.num = 123;</span></span><br><span class="line"><span class="comment">//module.exports.age = 18;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//通过module.exports也可以导出一个值，但是多次导出会覆盖</span></span><br><span class="line"><span class="built_in">module</span>.exports = <span class="string">'123'</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = <span class="string">"abc"</span>;</span><br></pre></td></tr></table></figure>



<h3 id="module-exports与exports"><a href="#module-exports与exports" class="headerlink" title="module.exports与exports"></a>module.exports与exports</h3><ul>
<li><code>exports</code> 是 <code>module.exports</code> 的引用</li>
<li>注意：给 <code>module.exports</code> 赋值会切断与 <code>exports</code> 之间的联系<ul>
<li>1 直接添加属性两者皆可</li>
<li>2 赋值操作时，只能使用 <code>module.exports</code></li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log( <span class="built_in">module</span>.exports === exports ) <span class="comment">// ==&gt; true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 等价操作</span></span><br><span class="line"><span class="built_in">module</span>.exports.num = <span class="number">123</span></span><br><span class="line">exports.num = <span class="number">123</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 赋值操作：不要使用 exports = &#123;&#125;</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="第三方模块（以mime包为例）"><a href="#第三方模块（以mime包为例）" class="headerlink" title="第三方模块（以mime包为例）"></a>第三方模块（以mime包为例）</h3><ul>
<li>先基于当前文件模块所属目录找 node_modules 目录</li>
<li>如果找到，则去该目录中找 mime 目录</li>
<li>如果找到 mime 目录，则找该目录中的 package.json 文件</li>
<li>如果找到 package.json 文件，则找该文件中的 main 属性</li>
<li>如果找到 main 属性，则拿到该属性对应的文件路径</li>
<li>如果找到 mime 目录之后<ul>
<li>发现没有 package.json</li>
<li>或者 有 package.json 没有 main 属性</li>
<li>或者 有 main 属性，但是指向的路径不存在</li>
<li>则 node 会默认去看一下 mime 目录中有没有 index.js index.node index.json 文件</li>
</ul>
</li>
<li>如果找不到 index 或者找不到 mime 或者找不到 node_modules</li>
<li>则进入上一级目录找 node_moudles 查找规则同上</li>
<li>如果上一级还找不到，继续向上，一直到当前文件所属磁盘根目录</li>
<li>如果最后到磁盘根目录还找不到，最后报错：<code>can not find module xxx</code></li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/node-%E6%A8%A1%E5%9D%97%E5%8C%96/" rel="tag"># node 模块化</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/" rel="prev" title="node基础">
      <i class="fa fa-chevron-left"></i> node基础
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/" rel="next" title="express">
      express <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#模块化"><span class="nav-text">模块化</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#基本概念"><span class="nav-text">基本概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#node中模块分类"><span class="nav-text">node中模块分类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#核心模块"><span class="nav-text">核心模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第三方模块"><span class="nav-text">第三方模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用户自定义模块"><span class="nav-text">用户自定义模块</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#模块的导入与导出"><span class="nav-text">模块的导入与导出</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#模块导入"><span class="nav-text">模块导入</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#模块导出"><span class="nav-text">模块导出</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#module-exports与exports"><span class="nav-text">module.exports与exports</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第三方模块（以mime包为例）"><span class="nav-text">第三方模块（以mime包为例）</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="大春哥"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">大春哥</p>
  <div class="site-description" itemprop="description">IT</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">35</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大春哥</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
